/*
 * ExtendedChatMessage.cpp
 */

#include "ExtendedChatMessage.h"

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using boost::property_tree::ptree;

#include <boost/random/uniform_int.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <ctime>
#include <limits>

vsznDefault(ExtendedChatMessage);

ExtendedChatMessage::ExtendedChatMessage()
{
	// Default constructor is necessary for serialization
}

ExtendedChatMessage::~ExtendedChatMessage()
{
}

string ExtendedChatMessage::getXml(bool isEcho)
{
	ptree subtree;
	subtree.put("from", this->from);
	subtree.put("to", this->to);
	subtree.put("id", this->messageId);
	subtree.put("time_stamp", this->timeStamp);
	subtree.put("text", this->text);
	
	ptree ptree;
	if (isEcho)
	{
		ptree.put_child("chatecho", subtree);
	}
	else
	{
		ptree.put_child("chat", subtree);
	}

	ostringstream sstream;
	write_xml(sstream, ptree);
	return sstream.str();
}

void ExtendedChatMessage::parseXml(ptree& pt)
{
	// the UI might very likely not provide a <from>, if so use the preset one
	this->from = pt.get("chat.from", this->from);
	
	this->to = pt.get<string>("chat.to");
	
	/* if no message ID is provided generate a random one */
	// set up random number generator only once
	static boost::mt19937 generator(clock());
	static boost::uniform_int<uint32_t>
		distribution(1, numeric_limits<uint32_t>::max());
	
	this->messageId = pt.get("chat.id", distribution(generator));
	
	
	ptime now = boost::posix_time::second_clock::universal_time();
	this->timeStamp = pt.get("chat.time_stamp", now);
	
	this->text = pt.get<string>("chat.text");
	
}

